package com.zehua.controller;

import com.zehua.entity.User;
import com.zehua.util.PageCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import com.zehua.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("/getUsers")
    public String getUsers(Model model){
        List<User> list=userService.getUsers();
        if (list.size()>0) {
            model.addAttribute("list", list);
        }
        return "users";
    }

    public ModelAndView getUsersByPage(int pageindex){

        ModelAndView modelAndView= new ModelAndView();
        int userCount= userService.getUserCount();
        int totalPages= PageCommon.getTotalPages(userCount,PageCommon.PAGE_SIZE);

        if (pageindex==0)
            pageindex=1;

        if (pageindex>totalPages)
            pageindex=totalPages;

        Map<String,Integer> cond =new HashMap<>();
        cond.put("start", PageCommon.PAGE_SIZE*(pageindex-1));
        cond.put("length", PageCommon.PAGE_SIZE);

        List<User> list=userService.getUsersByPage(cond);

        modelAndView.addObject("pageindex",pageindex);
        modelAndView.addObject("list",list);
        modelAndView.addObject("totalPages",totalPages);
        modelAndView.setViewName("users");

        return modelAndView;
    }
}
